package com.atg.atgchat.init.user.wxmp.service.imp;

import com.atg.atgchat.init.common.utils.JwtUtils;
import com.atg.atgchat.init.common.utils.RedisUtils;
import com.atg.atgchat.init.config.ThreadPoolConfig;
import com.atg.atgchat.init.constant.RedisKey;
import com.atg.atgchat.init.user.wxmp.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/*
author: atg
time: 2025/1/14 14:50
*/
@Service
public class LoginServiceImp  implements LoginService {
    public static final int TOKEN_RENEWAL_DAYS = 1;
    @Resource
    private JwtUtils jwtUtils;
    @Override
    public String login(Long id) {
        String token = jwtUtils.createToken(id);
        RedisUtils.set(RedisKey.getKey(RedisKey.USER_TOKEN_KEY, id), token, 3, TimeUnit.DAYS);
        return token;
    }
    // 刷新token有效期--延期
    // 线程问题
    @Override
    @Async(ThreadPoolConfig.ATGCHAT_EXECUTOR)
    public void renewalTokenIfNecessary(String token) {
        Long Uid = getValidUid(token);
        String userTokenKey = getToken(Uid);
        Long expire = RedisUtils.getExpire(userTokenKey, TimeUnit.DAYS);
        if (expire == -2){
            return;
        }
        if (expire < TOKEN_RENEWAL_DAYS){
            RedisUtils.expire(userTokenKey, 3, TimeUnit.DAYS);
        }

    }

    // 前端传递token进行验证
    // 前端传递token进行验证-生成uid--后端验证uid是否存在--不存在则返回null--存在则返回uid
    @Override  // 验证
    public Long getValidUid(String token) {
//        生成uid
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return null;
        }
//        后端验证uid是否存在
        String oldToken =  RedisUtils.getStr(getToken(uid));
        if(StringUtils.isBlank(oldToken)){
            return null;
        }
//        不存在则返回null--存在则返回uid
        return Objects.equals(oldToken, token) ? uid : null;
    }
    private String getToken(Long uid) {
        String key = RedisKey.getKey(RedisKey.USER_TOKEN_KEY, uid);
        return key;
    }
}
